package cn.faifai.desktop.config;

import cn.faifai.common.constant.SystemConstant;
import cn.faifai.common.utils.SpringContextUtil;
import cn.faifai.desktop.utils.StageManager;
import javafx.application.Platform;
import javafx.stage.Stage;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

/**
 * 单例模式获取托盘实例，避免重复实例化
 */
@Slf4j
@Getter
public class TrayManager {
    private static TrayManager instance;
    private TrayIcon trayIcon;
    private List<MenuItem> menuItems;
    private List<Function> destroyActions;

    private TrayManager() { // 私有构造方法防止外部实例化
        initTray();
    }

    public static synchronized TrayManager getInstance() {
        if (instance == null) {
            instance = new TrayManager();
        }
        return instance;
    }

    private void initTray() {

        // 初始化托盘图标、菜单等
        Image faiIcon = Toolkit.getDefaultToolkit().getImage("/ICON/白fai.ico");
        trayIcon = new TrayIcon(faiIcon, SpringContextUtil.getContext().getBean(SystemConstant.class).getID());
        // 创建默认菜单项
        menuItems = new ArrayList<>();
        // ... 初始化菜单项并绑定事件
        try {
            SystemTray.getSystemTray().add(trayIcon);
        } catch (AWTException e) {
            log.error("创建系统托盘失败");
            throw new RuntimeException(e);
        }

        // 将窗口隐藏到托盘
        if (SystemTray.isSupported()){
            SystemTray tray = SystemTray.getSystemTray();
            // 新建弹窗
            PopupMenu popup = new PopupMenu();

            // 新建退出菜单
            MenuItem exitItem = new MenuItem("exit");
            exitItem.addActionListener(e -> {
                Platform.exit();
                this.destroy();
                // 关闭springboot
                log.info("关闭springboot");
                SpringContextUtil.getContext().close();
            });
            popup.add(exitItem);

            // 设置托盘图标单击行为
            getTrayIcon().addActionListener(e -> Platform.runLater(() -> {
                log.info("重新显示窗口");
                Stage beginStage = StageManager.getInstance().getStage("MainStage");
                beginStage.show();
                beginStage.setIconified(false);
            }));

            getTrayIcon().setPopupMenu(popup);
        }
    }

    public void updateMenuItemState(int index, boolean enabled) {
        // 动态控制菜单项状态（如禁用第二项）
        if (index >= 0 && index < menuItems.size()) {
            Platform.runLater(() -> menuItems.get(index).setEnabled(!enabled));
        }
    }

    public void destroy() {
        // 显式释放资源
        SystemTray.getSystemTray().remove(trayIcon);
        instance = null;
        if (destroyActions != null) destroyActions.forEach(action -> action.apply(null));
    }

    public void addDestroyAction(Function action) {
        if (destroyActions == null) {
            destroyActions = new ArrayList<>();
        }
        destroyActions.add(action);
    }
}
